import axios from 'axios'

// 创建专用的axios实例
const api = axios.create({
    baseURL: import.meta.env.VITE_APP_API_URL,
    timeout: 30000, // AI请求可能需要更长时间
    headers: {
        'Content-Type': 'application/json',
    },
})

// 请求拦截器
api.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => Promise.reject(error)
)

// 响应拦截器
api.interceptors.response.use(
    (response) => response,
    (error) => {
        console.error('AI客服API请求错误:', error)
        return Promise.reject(error)
    }
)

// 聊天请求接口
export interface ChatRequest {
    message: string
    sessionId?: string
}

// 聊天响应接口
export interface ChatResponse {
    reply: string
    sessionId: string
    requestId?: string
    usage?: {
        inputTokens: number
        outputTokens: number
        totalTokens: number
    }
    timestamp: string
}

// 消息接口
export interface ChatMessage {
    role: 'user' | 'assistant' | 'system'
    content: string
    timestamp: string
    usage?: {
        inputTokens: number
        outputTokens: number
        totalTokens: number
    }
}

// API响应包装接口
export interface ApiResponse<T> {
    success: boolean
    data: T
    message: string
    error?: string
}

/**
 * AI智能客服API服务
 */
export class AiCustomerServiceApi {
    private static readonly BASE_URL = '/AiCustomer'

    /**
 * 发送聊天消息
 */
    static async sendMessage(request: ChatRequest): Promise<ChatResponse> {
        const response = await api.post<ApiResponse<ChatResponse>>(
            `${this.BASE_URL}/chat`,
            request
        )

        const result = response.data
        if (!result.success) {
            throw new Error(result.error || result.message || '发送消息失败')
        }

        return result.data
    }

    /**
     * 获取聊天历史记录
     */
    static async getChatHistory(sessionId: string): Promise<ChatMessage[]> {
        const response = await api.get<ApiResponse<ChatMessage[]>>(
            `${this.BASE_URL}/history/${sessionId}`
        )

        const result = response.data
        if (!result.success) {
            throw new Error(result.error || result.message || '获取历史记录失败')
        }

        return result.data
    }

    /**
     * 清除聊天历史记录
     */
    static async clearChatHistory(sessionId: string): Promise<void> {
        const response = await api.delete<ApiResponse<void>>(
            `${this.BASE_URL}/history/${sessionId}`
        )

        const result = response.data
        if (!result.success) {
            throw new Error(result.error || result.message || '清除历史记录失败')
        }
    }

    /**
     * 获取智能推荐回复
     */
    static async getSuggestedReplies(context: string): Promise<string[]> {
        const response = await api.post<ApiResponse<string[]>>(
            `${this.BASE_URL}/suggestions`,
            context
        )

        const result = response.data
        if (!result.success) {
            throw new Error(result.error || result.message || '获取推荐回复失败')
        }

        return result.data
    }

    /**
     * 分析用户意图
     */
    static async analyzeUserIntent(message: string): Promise<string> {
        const response = await api.post<ApiResponse<{ intent: string }>>(
            `${this.BASE_URL}/analyze-intent`,
            message
        )

        const result = response.data
        if (!result.success) {
            throw new Error(result.error || result.message || '分析用户意图失败')
        }

        return result.data.intent
    }

    /**
     * 健康检查
     */
    static async healthCheck(): Promise<boolean> {
        try {
            const response = await api.get<ApiResponse<void>>(
                `${this.BASE_URL}/health`
            )
            return response.data.success
        } catch {
            return false
        }
    }

    /**
     * 检查服务健康状态
     */
    static async checkHealth(): Promise<any> {
        try {
            const response = await api.get<ApiResponse<any>>(
                `${this.BASE_URL}/health`
            )

            if (response.data.success) {
                return {
                    status: 'healthy',
                    message: '服务正常',
                    timestamp: new Date().toISOString()
                }
            } else {
                return {
                    status: 'error',
                    message: response.data.message || '服务异常',
                    timestamp: new Date().toISOString()
                }
            }
        } catch (error) {
            return {
                status: 'error',
                message: '服务连接失败',
                timestamp: new Date().toISOString()
            }
        }
    }

    /**
     * 获取服务信息
     */
    static async getServiceInfo(): Promise<any> {
        const response = await api.get<ApiResponse<any>>(
            `${this.BASE_URL}/info`
        )

        const result = response.data
        if (!result.success) {
            throw new Error(result.error || result.message || '获取服务信息失败')
        }

        return result.data
    }
}

export default AiCustomerServiceApi 